package com.zyl.pts.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * @version v1.0
 * @ProjectName: product_source
 * @Package: com.zyl.pts.utils
 * @ClassName: OssUtil
 * @Description TODO(七牛云OSS对象存储服务)
 * @Author 翟玉龙
 * @Date 2024/11/20-15:07
 */
@Data
@Component
@ConfigurationProperties(prefix = "oss")
public class OssUtil {
    //AK
    private String accessKey;
    //SK
    private String secretKey;
    //桶
    private String bucket;
    //基础域名
    private String baseUrl;

    /**
     * 文件上传核心方法
     * @param imgFile 上传的文件
     */
    public String uploadOss(MultipartFile imgFile){
        /*
            构造一个带指定 Region 对象的配置类
            (根据七牛云服务器地区进行设置，这里autoRegion会自动匹配相应地区七牛云服务)
         */
        Configuration configuration = new Configuration(Region.autoRegion());
        /*
            将配置传入UploadManager
         */
        UploadManager uploadManager = new UploadManager(configuration);

        /*
            默认不指定key的情况下，以文件内容的hash值作为文件名
         */
        try {
            /*
                选择文件路径进行上传（根据上传的文件转换成输入流）
             */
            InputStream inputStream = imgFile.getInputStream();
            /*
                验证AK与SK
             */
            Auth auth = Auth.create(accessKey, secretKey);
            /*
                指定桶，仓库名称
             */
            String upToken = auth.uploadToken(bucket);

            String filePath = CUtil.UUID() + getExtension(imgFile.getOriginalFilename());
            try {
                Response response = uploadManager.put(inputStream, filePath , upToken,null, null);
                /*
                    解析上传成功的结果
                 */
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                /*
                    打印key
                 */
                CUtil.logInfo("key: " + putRet.key);
                /*
                    打印hash
                 */
                CUtil.logInfo("hash: " + putRet.hash);
                /*
                    返回访问路径
                 */
                CUtil.logInfo("图片上传成功，访问地址：" + baseUrl + "/" + putRet.key);
                /*
                    返回静态资源访问URL
                 */
                return baseUrl + "/" + putRet.key;
            } catch (QiniuException ex) {
                /*
                    打印错误信息
                 */
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    CUtil.logError("上传图片失败，失败原因：" + ex2);
                }
            }
        } catch (Exception ex) {
            CUtil.logError("上传图片失败，失败原因：" + ex);
        }
        return null;
    }

    /**
     * 获取文件后缀名
     * @param originalFilename 文件名
     * @return {@link String }
     */
    private String getExtension(String originalFilename) {
        if (originalFilename == null || originalFilename.isEmpty()) {
            return "";
        }
        int lastIndexOfDot = originalFilename.lastIndexOf(".");
        if (lastIndexOfDot == -1) {
            return "";
        }
        return originalFilename.substring(lastIndexOfDot);
    }
}
